import { hasToken, getLocalChannels, setLocalChannels } from '@/utils/storage';

import { delUserChannelsAPI } from '@/api/channel';
import { getAllChannelsAPI, getUserChannelsAPI, setUserChannelsAPI } from '@/api/channel';
import { AppDispatch } from '..';
import { ChannelActionType, ChannelType } from '../reducer/channel';

export const getAllChannelAction = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getAllChannelsAPI();
    dispatch({ type: 'channel/saveChannels', payload: res.data.channels });
  };
};

export const getUserChannelAction = () => {
  return async (dispatch: AppDispatch) => {
    if (hasToken()) {
      const res = await getUserChannelsAPI();
      dispatch({ type: 'channel/saveUserChannels', payload: res.data.channels });
    } else {
      const localList = getLocalChannels();

      if (!!localList.length) {
        dispatch({ type: 'channel/saveUserChannels', payload: localList });
      } else {
        const res = await getAllChannelsAPI();

        const tenList = res.data.channels.slice(0, 10);
        dispatch({ type: 'channel/saveUserChannels', payload: tenList });
        setLocalChannels(tenList);
      }
    }
  };
};

export const setUserChannelAction = (newItem: ChannelType) => {
  return async (dispatch: AppDispatch) => {
    if (hasToken()) {
      await setUserChannelsAPI({ channels: [newItem] });
      dispatch({ type: 'channel/updateUserChannels', payload: newItem });
      return;
    }

    const localList = getLocalChannels();
    setLocalChannels([...localList, newItem]);
    dispatch({ type: 'channel/updateUserChannels', payload: newItem });
  };
};
export const delUserChannelAction = (id: number) => {
  return async (dispatch: AppDispatch) => {
    if (hasToken()) {
      await delUserChannelsAPI(id);
      dispatch({ type: 'channel/delUserChannels', payload: id });
      return;
    }

    const localList = getLocalChannels();
    setLocalChannels(localList.filter((v) => v.id !== id));
    dispatch({ type: 'channel/delUserChannels', payload: id });
  };
};

// 3. 修改action的参数类型
export const setChannelIdAction = (id: number): ChannelActionType => {
  return {
    type: 'channel/setChannelId',
    payload: id,
  };
};
